local skynet = require "skynet"
local mysql = require "skynet.db.mysql"
local cjson = require "cjson"

local db
local mysql_host = "127.0.0.1"
local mysql_port = 3306
local mysql_database = "skynetdemo"
local mysql_username = "root"
local mysql_password = "123456"

local function test1()
    print("this is test1")
    local timestamps = os.time()
    local username = "why"
    local password = 123
    local sql = string.format("insert into users(username, password, created, updated) values(%s, %s, %d, %d)",
        mysql.quote_sql_str(username), mysql.quote_sql_str(password), timestamps, timestamps)

    skynet.error("register query sql:", sql)
    local res = db:query(sql)

    print(cjson.encode(res))
end

local function test2()
    print("this is test2")
    local timestamps = os.time()
    local sql = string.format("update users set exp=%d where id=%d", 10, 5)
    skynet.error("update_exp query sql:", sql)

    local res = db:query(sql)

    print(cjson.encode(res))
end

skynet.start(function()
    local function on_connected(db)
        skynet.error("mysql connected!")
    end

    local ok
    ok, db = pcall(mysql.connect, {
        host = mysql_host,
        port = mysql_port,
        database = mysql_database,
        user = mysql_username,
        password = mysql_password,
        max_packet_size = 1024 * 1024,
        on_connect = on_connected
    })

    if not ok or not db then
        skynet.error("connect to mysql failed")
    end

    test2()
end)
